package org.xukai.remoting.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Client implements Runnable{

	private Selector selector;

	private static ByteBuffer writeBuf = ByteBuffer.allocate(1024);

	private static ByteBuffer readBuf = ByteBuffer.allocate(1024);

	//需要一个Selector 
	public Client() throws IOException {
		selector = Selector.open();
		//创建连接的地址
		InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8072);
		
		//声明连接通道
		SocketChannel sc = null;
		try {

			//打开通道
			sc = SocketChannel.open();
			//进行连接
			sc.connect(address);

			sc.configureBlocking(false);

			sc.register(selector, SelectionKey.OP_READ);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				selector.select();
				Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
				while (keys.hasNext()) {
					SelectionKey key = keys.next();
					keys.remove();
					if (key.isValid()) {
						if (key.isWritable()) {
							write(key);
						} else if (key.isReadable()) {
							read(key);
						}
					}
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
	private void read(SelectionKey key){
		SocketChannel sc = (SocketChannel) key.channel();
		try {
			int count = sc.read(readBuf);
			if (count == -1) {
				key.cancel();
			}
			readBuf.flip();
			byte[] bytes = new byte[readBuf.remaining()];
			readBuf.get(bytes);
			System.out.println(new String(bytes));
			readBuf.clear();
//			sc.register(selector,SelectionKey.OP_WRITE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//java 合并两个byte数组
	public static byte[] byteMerger(byte[] byte_1, byte[] byte_2){
		byte[] byte_3 = new byte[byte_1.length+byte_2.length];
		System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
		System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
		return byte_3;
	}
	private void write(SelectionKey key){
		SocketChannel sc = (SocketChannel) key.channel();
		writeBuf.put("客户端第一次".getBytes());
		writeBuf.flip();
		try {
			sc.write(writeBuf);
			writeBuf.clear();
			sc.register(selector,SelectionKey.OP_READ);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		try {
			byte[] bytes1 = {1};
			byte[] bytes2 = {2};
			byte[] bytes = byteMerger(bytes1, bytes2);
			new Thread(new Client()).start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
